package com.project.controller;

import com.project.entity.Users;
import com.project.service.UsersService;
import com.project.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Leo高洋
 * @create 2023-03-28 17:15
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UsersService usersService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/updatePassword")
    public R updatePassword(@RequestBody Users users) {
        Users currentUser = usersService.getById(users.getId());
        if (bCryptPasswordEncoder.matches(users.getOldPassword(), currentUser.getPassword())) {
            currentUser.setPassword(bCryptPasswordEncoder.encode(users.getNewPassword()));
            usersService.updateById(currentUser);
            return R.ok();
        } else {
            return R.error("原密码错误");
        }
    }
}
